﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class TypeSpecificationRule : ILRule<TypeSpecificationHandle>
    {
        public byte[] Signature { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public TypeSpecificationRule(
            byte[] signature)
            : base()
        {
            Signature = signature;
        }

        public TypeSpecificationRule(MetadataReader reader, TypeSpecificationHandle typeSpecificationHandle)
            : base(reader)
        {
            TypeSpecification typeSpecification = reader.GetTypeSpecification(typeSpecificationHandle);
            Signature = reader.GetBlobBytes(typeSpecification.Signature);
            CustomAttributes = typeSpecification.GetCustomAttributes();
        }

        public override TypeSpecificationHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddTypeSpecification(
                signature: Signature == null ? default : builder.GetOrAddBlob(Signature));
        }
    }
}